package git.soulbgm.controller;

import git.soulbgm.mapper.CommonMapper;
import git.soulbgm.utils.DateUtil;
import git.soulbgm.utils.ExcelUtil;
import git.soulbgm.utils.IoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 查询控制器
 *
 * @author SoulBGM
 * @date 2021-09-27
 */
@RestController
public class QueryController {

    @Resource
    private CommonMapper mapper;

    @PostMapping("select")
    public List<Map<String, Object>> select(String sql) {
        List<Map<String, Object>> data = mapper.commonSelect(sql);
        return data;
    }

    @GetMapping("export")
    public String export(@RequestParam("sqlPath") String sqlPath, @RequestParam("exportPath") String exportPath, HttpServletResponse response) {
        String fileName = "data_" + DateUtil.format(new Date(), DateUtil.FORMAT_YMDHMSS);
        String sql = IoUtil.getFileContent(new File(sqlPath));
        List<Map<String, Object>> data = mapper.commonSelect(sql);
        ExcelUtil.writerExcel(exportPath, fileName, data);
        return "success";
    }

}
